﻿using System;
using System.Collections.Generic;

namespace PersonLookup.ViewModel
{
    public partial class Persons
    {
        partial void ConstructorExecuting()
        {
            NewPerson = new Person();
            Collection = new PersonCollection();
        }

        partial void GetAllCompleted(PersonCollection persons, Exception error, object userState)
        {
            if (error == null)
            {
                this.Collection = persons;
            }
        }

        partial void AddPersonCommandExecute(object parameter)
        {
            this.Collection.Add(this.NewPerson);
            this.NewPerson.EntityStatus = MVVM.EntityStatus.Added;
            this.NewPerson = new Person();
        }

        partial void EditPersonCommandExecute(object parameter)
        {
            this.EditPerson = this.SelectedPerson;
            this.EditPerson.BeginEdit();
        }

        partial void DeletePersonCommandExecute(object parameter)
        {
            this.SelectedPerson.EntityStatus = MVVM.EntityStatus.Deleted;
        }

        partial void UpdateCommandExecute(object parameter)
        {
            var personsToDelete = new List<Person>();

            foreach (var person in Collection)
            {
                switch (person.EntityStatus)
                {
                    case MVVM.EntityStatus.Original:
                        // ignore
                        break;
                    case MVVM.EntityStatus.Added:
                        person.SaveCommand.Execute(null);
                        break;
                    case MVVM.EntityStatus.Modified:
                        person.UpdateCommand.Execute(null);
                        break;
                    case MVVM.EntityStatus.Deleted:
                        person.DeleteCommand.Execute(null);
                        personsToDelete.Add(person);
                        break;
                    default:
                        break;
                }
            }

            foreach (var personToDelete in personsToDelete)
            {
                Collection.Remove(personToDelete);
            }
        }

       
    }
}
